package com.jluzh10.learning.service.Impl;

import com.github.pagehelper.PageHelper;
import com.jluzh10.learning.dao.AnswerMapper;
import com.jluzh10.learning.dao.QuestionMapper;
import com.jluzh10.learning.domain.Answer;
import com.jluzh10.learning.domain.Question;
import com.jluzh10.learning.domain.QuestionExample;
import com.jluzh10.learning.service.AnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cj
 * @date 5/25/2019
 */
@Service
@Transactional
public class AnswerServiceImpl implements AnswerService {

    private final AnswerMapper answerMapper;

    private final QuestionMapper questionMapper;



    @Autowired
    public AnswerServiceImpl(AnswerMapper answerMapper, QuestionMapper questionMapper) {
        this.answerMapper = answerMapper;
        this.questionMapper = questionMapper;
    }



    /**
     * 插入一个回答,update该回答对应的问题表中的回答数量
     */
    public int addAnswer(Answer answer) {

        Question q = questionMapper.selectByPrimaryKey(answer.getQuestionId());//根据问题的id查询问题表中对应的问题
        int i = updateQuestion(q);//更新问题表
        if(i>0){//更新问题的回答数量成功
            return  answerMapper.insertSelective(answer);//更新回答
        } else {
            return 0;
        }

    }

    /**
     * 根据问题id查询该问题对应的所有回答
     * @param questionId
     * @return
     */
    @Override
    public List<Answer> searchAnswersService(Integer questionId) {
        return answerMapper.searchAnswers(questionId);
    }

    /**
     * update该回答对应的问题表中的问题的回答数量
     * @param q
     * @return
     */
    public int updateQuestion(Question q){
           int replyNum = q.getReplyNum();
           replyNum++;
           q.setReplyNum(replyNum);
          return questionMapper.updateByPrimaryKey(q);
    }





}
